using 后端服务.Models;

namespace 后端服务.Services;

/// <summary>
/// 视频服务实现类，处理视频相关的业务逻辑
/// </summary>
public class VideoService : IVideoService
{
    private readonly SqlQueryService _sqlQueryService;
    private readonly ILogger<VideoService> _logger;

    /// <summary>
    /// 构造函数，通过依赖注入初始化服务
    /// </summary>
    public VideoService(SqlQueryService sqlQueryService, ILogger<VideoService> logger)
    {
        _sqlQueryService = sqlQueryService;
        _logger = logger;
    }

    /// <summary>
    /// 内部类，用于处理包含TotalCount的查询结果
    /// </summary>
    private class VideoWithTotalCount : VideoDto
    {
        public int TotalCount { get; set; }
    }

    /// <summary>
    /// 搜索视频并返回分页结果
    /// </summary>
    public async Task<PagedResult<VideoDto>> SearchVideosAsync(string query, int page, int pageSize)
    {
        try
        {
            var offset = (page - 1) * pageSize;
            
            // 使用 Oracle 兼容的查询语法，避免使用可能与伪列冲突的别名
            var searchSql = @"
                WITH SearchResults AS (
                    SELECT 
                        v.VideoId,
                        v.Title,
                        v.Duration,
                        v.VideoUrl,
                        v.FileSize,
                        v.CreatedDate,
                        v.UpdatedDate,
                        COUNT(*) OVER() as TotalCount,
                        ROW_NUMBER() OVER(ORDER BY v.CreatedDate DESC) as ROW_POSITION
                    FROM VIDEOS v
                    WHERE LOWER(v.TITLE) LIKE '%' || LOWER(:query) || '%'
                )
                SELECT 
                    VideoId,
                    Title,
                    Duration,
                    VideoUrl,
                    FileSize,
                    CreatedDate,
                    UpdatedDate,
                    TotalCount
                FROM SearchResults
                WHERE ROW_POSITION > :offset AND ROW_POSITION <= :maxRow";

            var parameters = new Dictionary<string, object>
            {
                { ":query", query },
                { ":offset", offset },
                { ":maxRow", offset + pageSize }
            };

            var result = await _sqlQueryService.QueryAsync<VideoWithTotalCount>(searchSql, parameters);
            var totalCount = result.Any() ? result[0].TotalCount : 0;
            
            var videoDtos = result.Select(v => new VideoDto
            {
                VideoId = v.VideoId,
                Title = v.Title,
                Duration = v.Duration,
                VideoUrl = v.VideoUrl,
                FileSize = v.FileSize,
                CreatedDate = v.CreatedDate,
                UpdatedDate = v.UpdatedDate
            }).ToList();

            return new PagedResult<VideoDto>
            {
                Items = videoDtos,
                TotalCount = totalCount,
                PageNumber = page,
                PageSize = pageSize
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error occurred while searching videos");
            throw; // 让调用者处理异常
        }
    }

    /// <summary>
    /// 根据ID获取视频详情
    /// </summary>
    public async Task<VideoDto?> GetVideoByIdAsync(long id)
    {
        try
        {
            var sql = @"
                SELECT 
                    VideoId,
                    Title,
                    Duration,
                    VideoUrl,
                    FileSize,
                    CreatedDate,
                    UpdatedDate
                FROM VIDEOS 
                WHERE VideoId = :id";

            var parameters = new Dictionary<string, object>
            {
                { ":id", id }
            };

            var video = await _sqlQueryService.QueryAsync<VideoDto>(sql, parameters);
            return video.FirstOrDefault();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error occurred while retrieving video with ID {VideoId}", id);
            throw; // 让调用者处理异常
        }
    }

    /// <summary>
    /// 获取视频文件信息
    /// </summary>
    /// <param name="id">视频ID</param>
    /// <returns>返回包含文件信息的元组 (文件路径, 文件名, MIME类型)</returns>
    public async Task<(string? FilePath, string FileName, string MimeType)?> GetVideoFileInfoAsync(long id)
    {
        try
        {
            var video = await GetVideoByIdAsync(id);
            if (video == null || string.IsNullOrEmpty(video.VideoUrl))
                return null;

            var filePath = video.VideoUrl;
            if (!System.IO.File.Exists(filePath))
                return null;

            var fileName = Path.GetFileName(filePath);
            var extension = Path.GetExtension(filePath).ToLower();
            
            // 根据文件扩展名确定MIME类型
            var mimeType = extension switch
            {
                ".mp4" => "video/mp4",
                ".avi" => "video/x-msvideo",
                ".mov" => "video/quicktime",
                ".wmv" => "video/x-ms-wmv",
                ".flv" => "video/x-flv",
                ".mkv" => "video/x-matroska",
                _ => "application/octet-stream"
            };

            return (filePath, fileName, mimeType);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error occurred while getting video file info for ID {VideoId}", id);
            throw;
        }
    }
}